package com.mimo.logic.room.service.impl;

import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.mimo.common.room.event.RoomTopicEvent;
import com.mimo.common.utils.JsonUtils;
import com.mimo.logic.blocking.service.IAccessiableService;
import com.mimo.logic.metric.constants.MetricType;
import com.mimo.logic.metric.service.IMetricService;
import com.mimo.logic.room.service.IRoomCallback;

@Service
public class RoomCallbackImpl implements IRoomCallback {

  @Value("${logic.application.id}")
  private String applicationId;

  @Value("${logic.room.channel}")
  private String channel;

  @Autowired
  private IMetricService metricService;

  @Autowired
  private IAccessiableService userAccessiable;

  @Autowired
  private RedisTemplate<String, String> redisTemplate;

  @Override
  public void onCreated(String roomId) {
    this.send(RoomTopicEvent.createdEvent(applicationId, roomId));

    // 房间创建维度统计
    metricService.accumulate(MetricType.Room_Create, roomId);
  }

  @Override
  public void onDestroy(String roomId) {
    userAccessiable.onRoomDestory(roomId);// 房间清除时,同时清除房间上的各种封禁约束

    this.send(RoomTopicEvent.destoriedEvent(applicationId, roomId));
  }

  @Override
  public void onJoint(String roomId, String uid) {
    this.send(RoomTopicEvent.jointEvent(applicationId, roomId, uid));
  }

  @Override
  public void onLeft(String roomId, String uid) {
    this.send(RoomTopicEvent.leftEvent(applicationId, roomId, uid));
  }

  private void send(Object message) {
    Objects.requireNonNull(message);
    if (message instanceof String) {
      redisTemplate.convertAndSend(channel, message);
    } else {
      redisTemplate.convertAndSend(channel, JsonUtils.toJsonString(message));
    }
  }

}
